package ui.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPasswordField;

import server.boot.ServiceLoader;
import db.Database;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

public class MainFrame extends JFrame{

	private static final long serialVersionUID = -5863086312327279109L;
	private static final File settingFile = new File("settings");
	private JTextField isServingTF;
	JButton btnStart;
	JButton btnStop;
	private Settings set;
	private JTextField ipTF;
	private JTextField portTF;
	private JTextField usernameTF;
	private JPasswordField passwordField;
	private JButton btnSave;
	private JButton btnCancle;
	private JLabel lb1;
	private JLabel lb2;
	private JLabel lb3;
	private JLabel lb4;
	private JLabel lb5;
	private SystemTray st;
	private JButton btnHide;
	private JTextField databaseNameTF;

	public static void main(String[] args){
		MainFrame mf=new MainFrame();
		mf.setVisible(true);
	}
		
	
	
	private MainFrame(){
		this.setContentPane(new JPanel() {

			private static final long serialVersionUID = -8067534092982934270L;

			@Override
			public void paint(Graphics g) {
				this.setBackground(new Color(0, 0, 0, 0));
				Image background = Toolkit.getDefaultToolkit().getImage(
						"Graphics/framebackground.jpg");
				g.drawImage(background, 0, 0, null);
				super.paint(g);
			}
		});
		setDefaultCloseOperation(HIDE_ON_CLOSE);
		set=readSettings();
		setSize(450, 300);
		setResizable(false);
		getContentPane().setLayout(null);
		
		btnStart = new JButton("\u5F00\u59CB\u670D\u52A1");
		btnStart.addActionListener(e->startService());
		btnStart.setBounds(10, 10, 103, 23);
		getContentPane().add(btnStart);
		
		btnStop = new JButton("\u505C\u6B62\u670D\u52A1");
		btnStop.addActionListener(e->stopService());
		btnStop.setBounds(10, 10, 103, 23);
		btnStop.setVisible(false);
		getContentPane().add(btnStop);
		
		JButton btnExit = new JButton("\u9000\u51FA");
		
		btnExit.setBounds(10, 107, 103, 23);
		getContentPane().add(btnExit);
		btnExit.addActionListener(e->exit());
		
		JButton btnSettings = new JButton("\u914D\u7F6E");
		btnSettings.setBounds(10, 74, 103, 23);
		getContentPane().add(btnSettings);
		btnSettings.addActionListener(e->toSettings());
		
		isServingTF = new JTextField();
		isServingTF.setText("\u670D\u52A1\u5668\u5DF2\u505C\u6B62");
		isServingTF.setEditable(false);
		isServingTF.setBounds(10, 43, 103, 21);
		getContentPane().add(isServingTF);
		isServingTF.setColumns(10);
		
		ipTF = new JTextField();
		ipTF.setBounds(224, 11, 210, 21);
		getContentPane().add(ipTF);
		ipTF.setColumns(10);
		
		lb1 = new JLabel("\u6570\u636E\u5E93IP\uFF1A");
		lb1.setForeground(Color.WHITE);
		lb1.setBounds(123, 10, 91, 23);
		getContentPane().add(lb1);
		
		lb2 = new JLabel("\u6570\u636E\u5E93\u7AEF\u53E3\uFF1A");
		lb2.setForeground(Color.WHITE);
		lb2.setBounds(123, 74, 91, 23);
		getContentPane().add(lb2);
		
		portTF = new JTextField();
		portTF.setBounds(224, 75, 210, 21);
		getContentPane().add(portTF);
		portTF.setColumns(10);
		
		lb3 = new JLabel("\u6570\u636E\u5E93\u7528\u6237\u540D\uFF1A");
		lb3.setForeground(Color.WHITE);
		lb3.setBounds(123, 107, 93, 23);
		getContentPane().add(lb3);
		
		lb4 = new JLabel("\u6570\u636E\u5E93\u5BC6\u7801\uFF1A");
		lb4.setForeground(Color.WHITE);
		lb4.setBounds(123, 140, 91, 23);
		getContentPane().add(lb4);
		
		usernameTF = new JTextField();
		usernameTF.setBounds(224, 108, 210, 21);
		getContentPane().add(usernameTF);
		usernameTF.setColumns(10);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(224, 139, 210, 23);
		getContentPane().add(passwordField);
		
		btnSave = new JButton("\u4FDD\u5B58");
		btnSave.addActionListener(new ActionListener() {
			@SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent e) {
				set.databaseIP=ipTF.getText();
				set.databasePort=Integer.parseInt(portTF.getText());
				set.username=usernameTF.getText();
				set.password=passwordField.getText();
				set.databaseName=databaseNameTF.getText();
				saveSettings(set);
				toMain();}
		});
		btnSave.setBounds(157, 172, 93, 23);
		getContentPane().add(btnSave);
		
		btnCancle = new JButton("\u53D6\u6D88");
		btnCancle.addActionListener(e->toMain());
		btnCancle.setBounds(282, 172, 93, 23);
		getContentPane().add(btnCancle);
		
		btnHide = new JButton("\u9690\u85CF\u5230\u6258\u76D8");
		btnHide.setBounds(10, 107, 103, 23);
		btnHide.setVisible(false);
		btnHide.addActionListener(o->hideToTray());
		getContentPane().add(btnHide);
		
		databaseNameTF = new JTextField();
		databaseNameTF.setBounds(224, 43, 210, 23);
		getContentPane().add(databaseNameTF);
		databaseNameTF.setColumns(10);
		
		lb5 = new JLabel("\u6570\u636E\u5E93\u540D\u79F0\uFF1A");
		lb5.setForeground(Color.WHITE);
		lb5.setBounds(123, 40, 91, 26);
		getContentPane().add(lb5);
		
		
		Font font=new Font("微软雅黑", Font.PLAIN, 12);
		btnSettings.setFont(font);
		btnCancle.setFont(font);
		btnExit.setFont(font);
		btnStart.setFont(font);
		btnStop.setFont(font);
		btnHide.setFont(font);
		btnSave.setFont(font);
		isServingTF.setFont(font);
		
		if(SystemTray.isSupported()){
			try {
				showTray();
				btnExit.setBounds(10, 140, 103, 23);
				btnHide.setVisible(true);
			} catch (AWTException e1) {
				e1.printStackTrace();
			}
		}
		
		toMain();
	}
	
	private void toSettings(){
		lb1.setVisible(true);
		lb2.setVisible(true);
		lb3.setVisible(true);
		lb4.setVisible(true);
		lb5.setVisible(true);
		ipTF.setVisible(true);
		ipTF.setText(set.databaseIP);
		portTF.setVisible(true);
		portTF.setText(""+set.databasePort);
		usernameTF.setVisible(true);
		usernameTF.setText(set.username);
		passwordField.setVisible(true);
		passwordField.setText(set.password);
		databaseNameTF.setVisible(true);
		databaseNameTF.setText(set.databaseName);
		btnSave.setVisible(true);
		btnCancle.setVisible(true);
	}
	
	private void toMain(){
		lb1.setVisible(false);
		lb2.setVisible(false);
		lb3.setVisible(false);
		lb4.setVisible(false);
		lb5.setVisible(false);
		ipTF.setVisible(false);
		ipTF.setText("");
		portTF.setVisible(false);
		portTF.setText("");
		usernameTF.setVisible(false);
		usernameTF.setText("");
		passwordField.setVisible(false);
		passwordField.setText("");
		databaseNameTF.setVisible(false);
		databaseNameTF.setText("");
		btnSave.setVisible(false);
		btnCancle.setVisible(false);
	}
	
	private void showTray() throws AWTException{
		st=SystemTray.getSystemTray();
		Image image = Toolkit.getDefaultToolkit().getImage("Graphics/TrayIcon.png");
	    TrayIcon ti = new TrayIcon(image);  
	    ti.setToolTip ( "SEaC2进销存管理系统"); 
	    ti.addActionListener(e->this.setVisible(true));
	    PopupMenu popup=new PopupMenu();
	    MenuItem miexit=new MenuItem("Exit");
	    miexit.addActionListener(e->exit());
	    MenuItem mistart=new MenuItem("Start Service");
	    mistart.addActionListener(e->startService());
	    MenuItem mistop=new MenuItem("Stop Service");
	    mistart.addActionListener(e->stopService());
	    MenuItem mishowMain=new MenuItem("Show Main Window");
	    mishowMain.addActionListener(e->this.setVisible(true));
	    popup.add(mishowMain);
	    popup.add(mistart);
	    popup.add(mistop);
	    popup.add(miexit);
	    ti.setPopupMenu(popup);
		st.add(ti);
	}
	
	private void hideToTray(){
		this.dispose();
	}
	
	private void exit(){
		stopService();
		System.exit(0);
	}
	
	private void startService(){
		try {
			Database.iniDatabase(set.databaseIP, set.databasePort,set.databaseName, set.username, set.password);
			try {
				ServiceLoader.iniServiceLoader();
				isServingTF.setText("已开始服务");
				btnStart.setVisible(false);
				btnStop.setVisible(true);
			} catch (RemoteException e) {
				JOptionPane.showMessageDialog(this, "远程方法调用错误\n"+e.getMessage());
				e.printStackTrace();
			} catch (MalformedURLException e) {
				JOptionPane.showMessageDialog(this, "数据库地址错误\n"+e.getMessage());
				e.printStackTrace();
			} catch (AlreadyBoundException e) {
				JOptionPane.showMessageDialog(this, "服务器已经在运行，请勿打开多个服务器\n"+e.getMessage());
				e.printStackTrace();
			}
		}catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(this, "无法连接到数据库\n"+e.getMessage());
		}
	}
	
	private void stopService(){
		System.exit(0);
	}

	private Settings readSettings(){
		BufferedReader br;
		Settings s=new Settings();
		try {
			br=new BufferedReader(new FileReader(settingFile));
			s.username=br.readLine();
			s.password=br.readLine();
			s.databaseName=br.readLine();
			s.databaseIP=br.readLine();
			s.databasePort=Integer.parseInt(br.readLine());
			br.close();
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(this, "配置文件找不到，请填写配置信息\n"+e.getMessage());
			e.printStackTrace();
			s=new Settings();
			s.databaseIP="localhost";
			s.databasePort=3306;
		} catch (IOException|NumberFormatException e) {
			JOptionPane.showMessageDialog(this, "配置文件无法读取，请联系管理员，或重写填写配置信息\n"+e.getMessage());
			e.printStackTrace();
			s=new Settings();
			s.databaseIP="localhost";
			s.databasePort=3306;
		}
		return s;
	}
	
	private void saveSettings(Settings settings){
		OutputStreamWriter osw;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(settingFile));
			osw.write(settings.username+"\r\n");
			osw.write(settings.password+"\r\n");
			osw.write(settings.databaseName+"\r\n");
			osw.write(settings.databaseIP+"\r\n");
			osw.write(settings.databasePort+"\r\n");
			osw.close();
		}catch (IOException e) {
			JOptionPane.showMessageDialog(this, "配置文件无法写入，保存失败\n"+e.getMessage());
			e.printStackTrace();
		}
		
	}
	
	private class Settings{
		String username="";
		String password="";
		String databaseIP="";
		String databaseName="";
		int databasePort;
	}
}
